package com.yingsheng.bi.hks.template.element;

import com.yingsheng.bi.hks.basic.PUser;
import com.yingsheng.bi.hks.basic.consts.MsgDict;
import com.yingsheng.bi.hks.basic.consts.NameDict;
import com.yingsheng.bi.hks.basic.exception.ServiceRuntimeException;
import com.yingsheng.bi.hks.basic.utils.Subject;
import com.yingsheng.bi.hks.repository.redis.SubjectRedisService;
import com.yingsheng.bi.hks.template.events.ElementEvent;
import com.yingsheng.bi.hks.template.events.SimpleEvent;
import com.yingsheng.bi.hks.template.processor.ElementProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

public class SmsCodeVerifyElementProcessor implements ElementProcessor {

    @Autowired
    private SubjectRedisService subjectRedisService;

    @Override
    public void exec(ElementEvent event) {
        Object value = event.getInput();
        if (!ObjectUtils.isEmpty(value) && value instanceof String) {
            SimpleEvent simpleEvent = (SimpleEvent) event.getEvent();
            String channel = simpleEvent.getString(NameDict.CHANNEL);
            String mobile = getMobile(simpleEvent);
            String code = (String) value;
            if (!subjectRedisService.validSmsCode(channel, mobile, code)) {
                throw new ServiceRuntimeException(MsgDict.SMS_VERIFY_FAIL);
            }
        } else {
            throw new ServiceRuntimeException(MsgDict.SMS_VERIFY_FAIL);
        }
    }

    private String getMobile(SimpleEvent simpleEvent) {
        PUser user = Subject.get();
        if (user != null) {
            return user.getMobile();
        }
        return simpleEvent.getString(NameDict.MOBILE);
    }
}
